import "./index.less";
import logo from "../../asstes/images/logo.png";
import {Link, useLocation, useNavigate} from "react-router-dom";
import { Menu } from "antd";
// 引入菜单配置项
import menuList from "../../config/menuConfig";
/*左侧导航组件
 */
/*左侧导航组件*/
function LeftNav() {
    // 引入子菜单

    const SubMenu = Menu.SubMenu;

    // 菜单栏跳转
    const navigate = useNavigate()
    const menuClick = (route) =>{
        // console.log(route)
        navigate(route.key)
    }
    // 获取当前页面路径
    const currentPath = useLocation()
    console.log('当前页面路径',currentPath)
    if(currentPath.pathname.indexOf('/product') === 0){
        console.log('进入产品页面 和产品子路由页面')
        currentPath.pathname = '/product'
    }
    // 定一个函数来判断当前选中的路由是否需要打开，前提是有子路由
    const getOpenKey = (url_key,keys) => {
        let openKey = ''
        keys.forEach(item => {
            if(item.children){
                // 存在子路由
                item.children.forEach(
                    subItem =>{
                        if(url_key === subItem.key){
                            // 传入索引等于子路由索引  存储子路由索引
                            openKey = item.key
                        }
                        // 因为有嵌套列表所以需要采用递归调用
                        if(subItem.children){
                            getOpenKey(item.children)
                        }
                    }
                )
            }
        })
        // 返回存储的索引
        return openKey
    }
    // 渲染菜单项
    const menuNodes = (
        <Menu
            mode="inline"
            theme="dark"
            defaultSelectedKeys={["1"]}
            items={menuList}
            style={{ height: "100%", borderRight: 0 }}
            onClick={menuClick}
            selectedKeys={[currentPath.pathname]}
            defaultOpenKeys={[getOpenKey(currentPath.pathname,menuList)]}
        />
    );

    return (
        <div className="left-nav">
            <Link to={"/"} className="left-nav-header">
                <img src={logo} alt="logo" />
                <h3>云端后台</h3>
            </Link>
            {menuNodes}
        </div>
    );
}

export default LeftNav;
